package com.example.paimengshop.client_socket;

import com.example.paimengshop.AccountController;
import com.example.paimengshop.Data;
import com.example.paimengshop.dataclass.Commodity;
import com.example.paimengshop.dataclass.Order;
import com.example.paimengshop.dataclass.User;
import com.example.paimengshop.main;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class ActionControl_Receive
{

    private static JSONObject loginFeedbackJsonObject = new JSONObject();
    private static JSONObject registerFeedbackJsonObject = new JSONObject();
    private static JSONObject changePasswordFeedbackJsonObject = new JSONObject();



    public static void setLoginFeedbackJsonObject(JSONObject loginFeedbackJsonObject)
    {
        ActionControl_Receive.loginFeedbackJsonObject = loginFeedbackJsonObject;
    }

    public static JSONObject getLoginFeedbackJsonObject()
    {
        return loginFeedbackJsonObject;
    }

    public static void setRegisterFeedbackJsonObject(JSONObject registerFeedbackJsonObject)
    {
        ActionControl_Receive.registerFeedbackJsonObject = registerFeedbackJsonObject;
    }

    public static JSONObject getRegisterFeedbackJsonObject()
    {
        return registerFeedbackJsonObject;
    }

    public static void setChangePasswordFeedbackJsonObject(JSONObject changePasswordFeedbackJsonObject)
    {
        ActionControl_Receive.changePasswordFeedbackJsonObject = changePasswordFeedbackJsonObject;
    }

    public static JSONObject getChangePasswordFeedbackJsonObject()
    {
        return changePasswordFeedbackJsonObject;
    }

    public ActionControl_Receive()
    {

    }

    public static void LoginFeedback(JSONObject jsonObject)
    {
        if(!jsonObject.containsKey("without alert"))
        {
            String feedback = jsonObject.get("feedback").toString();
            if (feedback.equals("login succeed"))
            {
                loginFeedbackJsonObject.put("feedback", feedback);
                loginFeedbackJsonObject.put("id", jsonObject.get("id").toString());
            } else
            {
                loginFeedbackJsonObject.put("feedback", feedback);
            }
            AccountController.ShowLoginAlert();
        }
        else
        {
            main.getSend().Send(ActionControl_Send.AskForRefreshingUserInfo((Integer.parseInt(ActionControl_Receive.getLoginFeedbackJsonObject().get("id").toString()))));
        }
    }

    public static void RegisterFeedback(JSONObject jsonObject)
    {
        String feedback = jsonObject.get("feedback").toString();
        registerFeedbackJsonObject.put("feedback", feedback);
        AccountController.ShowRegisterAlert();
    }

    public static void ChangePasswordFeedback(JSONObject jsonObject)
    {
        String feedback = jsonObject.get("feedback").toString();
        changePasswordFeedbackJsonObject.put("feedback", feedback);
        AccountController.ShowChangePasswordAlert();
    }

    public static User ReceiveUserInfo(JSONObject jsonObject)
    {
        User user = new User();
        user.setId(Integer.parseInt(jsonObject.get("id").toString()));
        user.setUserName(jsonObject.get("userName").toString());
        user.setEmail(jsonObject.get("email").toString());
        user.setPassword(jsonObject.get("password").toString());
        user.setHeadImageURL(jsonObject.get("headImageURL").toString());
        user.setCart(Commodity.getCommodityArrayListFromString(jsonObject.get("cart").toString()));
        user.setCollection(Commodity.getCommodityArrayListFromString(jsonObject.get("collection").toString()));
        user.setAddress(jsonObject.get("address").toString());
        return user;
    }

    public static ArrayList<Commodity> ReceiveCommodityInfo(JSONArray jsonArray)
    {
        ArrayList<Commodity> commodityArrayList = new ArrayList<>();
        //第一个JSONObject是空的，跳过
        for(int i = 2; i < jsonArray.size(); i++)
        {
            JSONObject jsonObject = (JSONObject)jsonArray.get(i);
            Commodity commodity = new Commodity();
            commodity.setId(Integer.parseInt(jsonObject.get("id").toString()));
            commodity.setName(jsonObject.get("name").toString());
            commodity.setIntroduction(jsonObject.get("introduction").toString());
            commodity.setImageURL(jsonObject.get("imageURL").toString());
            commodity.setPrice(Double.parseDouble(jsonObject.get("price").toString()));
            commodityArrayList.add(commodity);
        }
        return commodityArrayList;
    }

    public static ArrayList<Order> ReceiveOrderInfo(JSONArray jsonArray)
    {
        ArrayList<Order> orderArrayList = new ArrayList<>();
        for(int i = 2; i < jsonArray.size(); i++)
        {
            JSONObject jsonObject = (JSONObject)jsonArray.get(i);
            Order order = new Order();
            order.setId(Integer.parseInt(jsonObject.get("id").toString()));
            order.setUserId(Integer.parseInt(jsonObject.get("userId").toString()));
            order.setAddress(jsonObject.get("address").toString());
            order.setCommodityList(Commodity.getCommodityArrayListFromString(jsonObject.get("commodityList").toString()));
            order.setCommodityNumber(Integer.parseInt(jsonObject.get("commodityNumber").toString()));
            order.setPayment(Double.parseDouble(jsonObject.get("payment").toString()));
            orderArrayList.add(order);
        }
        return orderArrayList;
    }

    public static String Communication_Message(JSONObject jsonObject)
    {
        return jsonObject.get("communication message").toString();
    }

    public static File Communication_Image(JSONObject jsonObject)
    {
        byte[] src = (byte[]) jsonObject.get("communication image");
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
        String imageName = dateFormat.format(date)+ ".jpg";
        String path = "PaiMengShop/PaiMengShopClient/src/main/resources/com/example/paimengshop/chatImage/" + imageName;
        File dest = new File(path);
        // 2、选择流
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new ByteArrayInputStream(src);
            os = new FileOutputStream(dest);
            // 3、操作(分段读取)
            byte[] flush = new byte[5];// 缓冲容器
            int len = -1;// 接收长度
            while ((len = is.read(flush)) != -1) {
                os.write(flush,0,len);
            }
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            try {
                if (null != os) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return dest;
    }
}
